# -*- coding: utf-8 -*-
# @FileName : Order.py
# @Time     : 2023/6/11 18:04
# @Author   : Zhong Runke
from common.models.OrderRecord import OrderRecord
from web.controller.api import route_api
from common.models.Classify import Classify
from common.models.Goods import Goods
from flask import jsonify, request
from common.libs.UrlManager import UrlManager
from common.libs.Helper import getCurrentDate
from sqlalchemy.sql import or_
from common.libs.webase.WebaseService import WebaseService
from common.models.User import User
from application import app, db, root_path, r
import json
import os
from common.libs.UrlManager import UrlManager
from common.models.Address import Address
import decimal
from common.libs.pay.PayService import PayService
from common.models.Order import Order
from common.models.Wallet import Wallet

@route_api.route('/order/info', methods=['GET', 'POST'])
def orderInfo():
    resp = {'code':200, 'msg':'OK', 'data':{}}
    req = request.values
    print(req)
    params_goods = req['goods'] if 'goods' in req else None
    # 登录校验
    auth_cookie = request.headers.get("Authorization") if 'Authorization' in request.headers else ''
    if not auth_cookie:
        resp['code'] = -1
        resp['msg'] = '没有Authorization'
        return jsonify(resp)
    auth_info = auth_cookie.split("#")
    print(auth_info)

    user_info = User.query.filter_by(id=auth_info[-1], status=1).first()

    if not user_info:
        resp['code'] = -1
        resp['msg'] = '没有此用户'
        return jsonify(resp)

    params_goods_list = []
    if params_goods:
        params_goods_list = json.loads(params_goods)
    print(params_goods_list)
    good_dict = {}
    for item in params_goods_list:
        good_dict[item['id']] = item['number']
    good_ids = good_dict.keys()
    good_list = Goods.query.filter(Goods.id.in_(good_ids)).all()
    data_good_list = []
    yun_price = pay_price = decimal.Decimal(0.00)
    if good_list:
        for item in good_list:
            tmp_data = {
                'id': item.id,
                'name': item.name,
                'price': str(item.price),
                'pic_url': UrlManager.buildImageUrl(item.image),
                'number': good_dict[item.id]
            }
            pay_price = pay_price + item.price * int(float(good_dict[item.id]))
            data_good_list.append(tmp_data)

    # 获取地址
    address_info = Address.query.filter_by(is_default=1, userAddress=user_info.address, status=1).first()
    default_address = ''
    if address_info:
        default_address = {
            "id": address_info.id,
            "name": address_info.nickname,
            "mobile": address_info.mobile,
            "address": "%s%s%s%s" % (address_info.province_str, address_info.city_str, address_info.area_str, address_info.address)
        }

    resp['data']['food_list'] = data_good_list
    resp['data']['pay_price'] = str(pay_price)
    resp['data']['yun_price'] = str(yun_price)
    resp['data']['total_price'] = str(pay_price + yun_price)
    resp['data']['default_address'] = default_address
    return jsonify(resp)


@route_api.route('/order/create', methods=['POST'])
def orderCreate():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values
    print(req)
    type = req['type'] if 'type' in req else ''
    note = req['note'] if 'note' in req else ''
    express_address_id = int(req['express_address_id']) if 'express_address_id' in req and req[
        'express_address_id'] else 0
    params_goods = req['goods'] if 'goods' in req else None

    items = []
    if params_goods:
        items = json.loads(params_goods)

    if len(items) < 1:
        resp['code'] = -1
        resp['msg'] = '下单失败，没有选择商品'
        return jsonify(resp)

    address_info = Address.query.filter_by(id=express_address_id).first()
    if not address_info or not address_info.status:
        resp['code'] = -1
        resp['msg'] = '下单失败，快递地址不对'
        return jsonify(resp)

    # 登录校验
    auth_cookie = request.headers.get("Authorization") if 'Authorization' in request.headers else ''
    if not auth_cookie:
        resp['code'] = -1
        resp['msg'] = '没有Authorization'
        return jsonify(resp)
    auth_info = auth_cookie.split("#")
    print(auth_info)

    user_info = User.query.filter_by(id=auth_info[-1], status=1).first()

    if not user_info:
        resp['code'] = -1
        resp['msg'] = '没有此用户'
        return jsonify(resp)

    target = PayService()
    params = {
        "note": note,
        "express_address_id": address_info.id,
        "express_info": {
            'mobile': address_info.mobile,
            'nickname': address_info.nickname,
            'address': '%s%s%s%s' % (address_info.province_str, address_info.city_str, address_info.area_str, address_info.address)
        }
    }
    print("==========slssksskksss===========")
    print(items)
    resp = target.createOrder(user_info.address, items, params)
    print(resp)

    # 已经创建订单的话要修改商品的状态
    return jsonify(resp)


def orderList():
    pass

# 取消订单
@route_api.route('/order/ops', methods=['POST'])
def orderOps():
    resp = {'code': 200, 'msg': 'OK', 'data': {}}
    # 登录校验
    auth_cookie = request.headers.get("Authorization") if 'Authorization' in request.headers else ''
    if not auth_cookie:
        resp['code'] = -1
        resp['msg'] = '没有Authorization'
        return jsonify(resp)
    auth_info = auth_cookie.split("#")
    print(auth_info)

    user_info = User.query.filter_by(id=auth_info[-1], status=1).first()

    if not user_info:
        resp['code'] = -1
        resp['msg'] = '没有此用户'
        return jsonify(resp)
    req = request.values
    order_sn = req['order_sn'] if 'order_sn' in req else ''
    act = req['act'] if 'act' in req else ''
    order_info = Order.query.filter_by(order_sn=order_sn, buyer=user_info.address).first()
    if not order_info:
        resp['code'] = -1
        resp['msg'] = '系统繁忙，请稍后再试'
        return jsonify(resp)

    if act == 'cancel':
        target_pay = PayService()
        ret = target_pay.closeOrder(order_id=order_info.id)
        if not ret:
            resp['code'] = -1
            resp['msg'] = '系统繁忙，请稍后再试'
            return jsonify(resp)
    elif act == 'confirm':
        order_info.express_status = 1
        order_info.updated_time = getCurrentDate()
        db.session.add(order_info)
        db.session.commit()
    return jsonify(resp)

@route_api.route("/order/pay", methods=['POST'])
def orderPay():
    resp = {'code':200, 'msg':'OK', 'data':{}}
    req = request.values
    # 登录校验
    auth_cookie = request.headers.get("Authorization") if 'Authorization' in request.headers else ''
    if not auth_cookie:
        resp['code'] = -1
        resp['msg'] = '没有Authorization'
        return jsonify(resp)
    auth_info = auth_cookie.split("#")
    print(auth_info)

    user_info = User.query.filter_by(id=auth_info[-1], status=1).first()

    if not user_info:
        resp['code'] = -1
        resp['msg'] = '没有此用户'
        return jsonify(resp)
    print(req)
    order_sn = req['order_sn'] if 'order_sn' in req else ''
    order_info = Order.query.filter_by(order_sn=order_sn, buyer=user_info.address).first()
    if not order_info:
        resp['code'] = -1
        resp['msg'] = '系统繁忙，请稍后再试'
        return jsonify(resp)

    # 修改钱包金额
    wallet_info = Wallet.query.filter_by(useraddress=user_info.address).first()
    if wallet_info.balance < order_info.price:
        resp['code'] = -1
        resp['msg'] = '钱包余额不足'
        return jsonify(resp)

    # 区块链交易
    # _number 流水号
    # _orderId webase的订单号
    webase_resp = WebaseService.commonReq(app.config['WEBASE_DEPLOYADDRESS'], "pay",
                                          [order_info.order_sn, order_info.orderIdCounter],
                                          app.config['WEBASE_CONTRACTABI'],
                                          app.config['WEBASE_CONTRACTNAME'],
                                          app.config['WEBASE_CONTRACTADDRESS'])

    webase_dict = json.loads(webase_resp)
    if webase_dict['message'] == 'Success':
        try:
            order_record_info = OrderRecord()
            order_record_info.order_sn = order_info.order_sn
            order_record_info.status = 2
            order_record_info.transactionhash = webase_dict['transactionHash']
            order_record_info.blocknum = webase_dict['blockNumber']
            order_record_info.blockHash = webase_dict['blockHash']
            order_record_info.created_time = order_record_info.updated_time = getCurrentDate()
            db.session.add(order_record_info)
            order_info.status = 1
            order_info.express_status = -7
            db.session.add(order_info)


            wallet_info.balance = wallet_info.balance - order_info.price
            db.session.add(wallet_info)
            db.session.commit()

            resp['data']['pay_info'] = {
                "pay_status": 'OK'
            }
        except Exception as e:
            db.session.rollback()

    else:
        resp['code'] = -1
        resp['msg'] = 'error'
    return jsonify(resp)

